#ifndef __FRAM_H
#define __FRAM_H

#ifdef __cplusplus
extern "C" {
#endif

#include "main.h"
#include "spi.h"
#include <stdint.h>
#include <stdbool.h>

// 8kb存储空间，总共8192字节，每页256字节
#define FRAM_SIZE                   8192
#define FRAM_PAGE_SIZE              256


#define FRAM_WREN                   0x06    // Write Enable
#define FRAM_WRDI                   0x04    // Write Disable
#define FRAM_RDSR                   0x05    // Read Status Register
#define FRAM_WRSR                   0x01    // Write Status Register
#define FRAM_READ                   0x03    // Read Data
#define FRAM_WRITE                  0x02    // Write Data
#define FRAM_FSTRD                  0x0B    // Fast Read
#define FRAM_SLEEP                  0xB9    // Sleep
#define FRAM_WAKE                   0xAB    // Wake


#define FRAM_SR_WPEN                0x80    // Write Protect Enable
#define FRAM_SR_BP1                 0x08    // Block Protect 1
#define FRAM_SR_BP0                 0x04    // Block Protect 0
#define FRAM_SR_WEL                 0x02    // Write Enable Latch
#define FRAM_SR_BUSY                0x01    // Busy

//数据存储结构定义
typedef struct {
    uint32_t timestamp;             // 时间戳
    float temperature;              // 温度
    float humidity;                 // 湿度
    uint16_t co2_level;            // CO2浓度
    uint16_t tvoc_level;           // TVOC浓度
    uint16_t ch2o_level;           // CH2O浓度
    uint8_t data_valid;            // 数据有效性标志
} sensor_data_t;


//存储管理结构
typedef struct {
    uint16_t write_index;          // 当前写入位置
    uint16_t read_index;           // 当前读取位置
    uint16_t data_count;           // 已存储的数据条数
    uint16_t max_records;          // 最大记录数字
} storage_manager_t;


//初始化写、读、擦除
bool FRAM_Init(void);
bool FRAM_WriteEnable(void);
bool FRAM_WriteDisable(void);
uint8_t FRAM_ReadStatus(void);
bool FRAM_WriteStatus(uint8_t status);
bool FRAM_Read(uint16_t address, uint8_t *data, uint16_t length);
bool FRAM_Write(uint16_t address, uint8_t *data, uint16_t length);
bool FRAM_ReadByte(uint16_t address, uint8_t *data);
bool FRAM_WriteByte(uint16_t address, uint8_t data);
bool FRAM_EraseAll(void);

// 
bool FRAM_InitStorage(void);
bool FRAM_SaveSensorData(sensor_data_t *data);
bool FRAM_ReadSensorData(uint16_t index, sensor_data_t *data);
uint16_t FRAM_GetDataCount(void);
bool FRAM_ClearAllData(void);
bool FRAM_GetLatestData(sensor_data_t *data);
bool FRAM_GetDataByTimeRange(uint32_t start_time, uint32_t end_time, sensor_data_t *data, uint16_t max_count, uint16_t *actual_count);

// 
bool FRAM_Save24HourData(sensor_data_t *data);
bool FRAM_Get24HourData(sensor_data_t *data, uint16_t max_count, uint16_t *actual_count);
bool FRAM_Is24HourDataAvailable(void);

#ifdef __cplusplus
}
#endif

#endif /* __FRAM_H */
